﻿using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Home.Framework.Infrastructure
{
    public static partial class DataHelper
    {
        /// <summary>
        /// 将DataRow行转换成EntityModel
        /// </summary>
        /// <param name="row"></param>
        /// <returns></returns>
        public static T ToEntityModel<T>(this DataRow row) where T : new()
        {
            T entity = new T();
            Type type = typeof(T);
            PropertyInfo[] properties = type.GetProperties();
            foreach (var property in properties)
            {
                if (property != null && row.Table.Columns.Contains(property.Name))
                {
                        //根据ColumnName，将dr中的相对字段赋值给Entity属性
                        property.SetValue(entity, Convert.ChangeType(row[property.Name], property.PropertyType), null);
                }
            }
            return entity;
        }

        /// <summary>
        /// 将DataTable行转换成List<EntityModel>
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="dt">The dt.</param>
        /// <returns>List{``0}.</returns>
        public static List<T> ToEntityList<T>(this DataTable table) where T : new()
        {
            List<T> list = new List<T>(table.Rows.Count);
            foreach (DataRow dr in table.Rows)
            {
                list.Add(dr.ToEntityModel<T>());
            }
            return list;
        }
    }
}
